package com.xhdx.ati.adau.controller.service.flow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xhdx.ati.adau.entity.ActivityEntity;
import com.xhdx.ati.adau.entity.TaskEntity;
import com.xhdx.ati.adau.util.StringUtils;
/**
 *  1.员工发起财务报销,附带金额信息(报销多少金额)
	2.单位领导审批,如果通过,交付经理审批,不通过,重新申请
	3.经理审批,如果报销金额不超过2000,经理1审批；如果报销金额在2000-5000,经理3审批；超过5000,经理2审批
	4.经理审批通过,流程结束,经理审批不通过,员工重新申请
	领导意见和经理意见,用0和1表示,0表示未通过,1表示通过
	${money<2000}经理1审批
	${money>=2000 && money<=5000}经理3审批
	${money>5000}经理2审批
 * @author lenovo
 *
 */
@Service
public class CwbxService {
	private static final Log logger = LogFactory.getLog(CwbxService.class);

	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private HistoryService historyService;

	// @Autowired
	// private RepositoryService repositoryService;

	/**职员提交申请 或者更新任务信息
	 * 
	 * @param taskId 发起的任务id
	 * @param processDefinitionKey 发起新流程必须传
	 * @param name 职员姓名
	 * @param money 报销金额
	 */
	public void completeEmployeeTask(String taskId, String processDefinitionKey, String name, Float money) {
		if(StringUtils.isEmpty(taskId)){
			taskId = startProcess(processDefinitionKey);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("money", money);
			variables.put("name", name);
			// 完成任务
			taskService.complete(taskId,variables);
			logger.info("职员已经提交申请.......");
		}else{
			taskService.setVariable(taskId, "money", money);
			taskService.setVariable(taskId, "name", name);
			// 更新完成任务
			taskService.complete(taskId);
			logger.info("职员已经更新并提交申请.......");
		}
	}

	/**领导审批
	 * 
	 * @param taskId 任务id,
	 * @param result 用0和1表示,0表示未通过,1表示通过
	 */
	public void completeLeaderTask(String taskId, Integer result) {
		Float money = null;
        try{
        	money = (Float) taskService.getVariable(taskId, "money");
        }catch(Exception e){
        }
		if(money!=null && money>5000 && result == 1){//经理02多了一参数，需要赋值
        	taskService.setVariable(taskId, "users", "test,test01");
        }
		// 领导意见
		Object on = taskService.getVariable(taskId, "leaderResult");
		if(on != null){//被打回的记录重新提交
			taskService.setVariable(taskId, "leaderResult", result);
			taskService.complete(taskId);
		}else{
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("leaderResult", result);
			// 完成任务
			taskService.complete(taskId, variables);
		}
		
        
		logger.info("领导审核完毕........");

	}

	/**经理审批
	 * 
	 * @param taskId 任务id
	 */
	public void completeMangerTask(String taskId, Integer result) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        
		// 获取任务id
		String name = task.getName();
		Object on = taskService.getVariable(taskId, "result");
		if(on != null){//被打回的记录重新提交
			taskService.setVariable(taskId, "result", result);
			taskService.complete(taskId);
		}else{
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("result", result);
			// 完成任务
			taskService.complete(taskId, variables);
		}
		logger.info("经理审核完毕........,审核经理:" + name);

	}
	/**
	 * 开启流程图一个新实例，获取任务id
	 */
	private String startProcess(String processDefinitionKey){
		Map<String, Object> variables = new HashMap<String, Object>();
		ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
		
		Task task = taskService.createTaskQuery()//创建查询对象
				.processInstanceId(pi.getId())//通过流程实例id来查询当前任务
				.singleResult();//获取单个查询结果
		
		return task.getId();
	}
	/**
	 * 查询每个节点任务(查询某人自己提交的任务/查询领导任务/查询经理任务)
	 */
	public List<TaskEntity>  queryTasks(String processDefinitionKey, String taskDefinitionKey, String applyName) {
		TaskQuery s1 = taskService.createTaskQuery();
		if(StringUtils.isNotEmpty(processDefinitionKey)){//根据流程定义key查询任务
			s1.processDefinitionKey(processDefinitionKey);
		}
		if(StringUtils.isNotEmpty(taskDefinitionKey)){//根据每个节点任务key查询任务
			s1.taskDefinitionKey(taskDefinitionKey);
		}
		List<Task> taskList = s1.list();
		
		//任务列表的展示
		List<TaskEntity> a = changeTasks(taskList, applyName);
        return a;
	}
	/**
	 * 任务转换
	 * @return
	 */
	private List<TaskEntity> changeTasks(List<Task> taskList, String applyName1){
		List<TaskEntity> taskEntityList = null;
		if(taskList!=null && taskList.size()>0){
			taskEntityList = new ArrayList<TaskEntity>(taskList.size());
			
			TaskEntity te = null;
			for(Task task :taskList){	            
	            logger.info("任务ID"+task.getId());
	            logger.info("任务名称"+task.getName());
	            logger.info("任务创建时间"+task.getCreateTime());
	            logger.info("任务的办理人"+task.getAssignee());
	            logger.info("流程实例id:"+task.getProcessInstanceId());
	            logger.info("执行对象id:"+task.getExecutionId());
	            logger.info("流程定义id:"+task.getProcessDefinitionId());
	            
	            te = new TaskEntity();
	            te.setProcessInstanceId(task.getProcessInstanceId());
	            te.setId(task.getId());
	            te.setAssignee(task.getAssignee());
	            te.setName(task.getName());
	            te.setCreateTime(task.getCreateTime());
	            te.setExecutionId(task.getExecutionId());
	            te.setProcessDefinitionId(task.getProcessDefinitionId());
	           
	            String applyName = null;
	            try{
	            	Float money = (Float) taskService.getVariable(task.getId(), "money");
	            	applyName = (String) taskService.getVariable(task.getId(), "name");
		    		te.setMoney(money);
		    		te.setApplyName(applyName);
	            }catch(Exception e){
	            }
	            if(StringUtils.isEmpty(applyName1)){
	            	taskEntityList.add(te);
	            }else{
	            	if(applyName != null && applyName1.equals(applyName)){
	            		taskEntityList.add(te);
	            	}
	            }
	            
	        }
		}
		
		return taskEntityList;
	}
	
    /**
     * 历史活动查询
     */
    public List<ActivityEntity> historyActInstanceList(String processInstanceId){
        List<HistoricActivityInstance>  list= historyService // 历史相关Service
            .createHistoricActivityInstanceQuery() // 创建历史活动实例查询
            .processInstanceId(processInstanceId) // 执行流程实例id
            .finished()
            .list();
        List<ActivityEntity> taskEntityList = new ArrayList<ActivityEntity>();
        ActivityEntity te = null;
        for(HistoricActivityInstance hai:list){
        	te = new ActivityEntity();
            logger.info("活动ID:"+hai.getId());
            te.setId(hai.getId());
            logger.info("流程实例ID:"+hai.getProcessInstanceId());
            te.setProcessInstanceId(hai.getProcessInstanceId());
            logger.info("活动名称："+hai.getActivityName());
            te.setActivityName(hai.getActivityName());
            logger.info("办理人："+hai.getAssignee());
            te.setAssignee(hai.getAssignee());
            logger.info("开始时间："+hai.getStartTime());
            te.setStartTime(hai.getStartTime());
            logger.info("结束时间："+hai.getEndTime());
            te.setEndTime(hai.getEndTime());
            logger.info("=================================");
            taskEntityList.add(te);
        }
        return taskEntityList;
    }
    /**
     * 历史任务查询
     */
    public List<TaskEntity> historyTaskList(String processInstanceId){
        List<HistoricTaskInstance> list= historyService // 历史相关Service
            .createHistoricTaskInstanceQuery() // 创建历史任务实例查询
            .processInstanceId(processInstanceId) // 用流程实例id查询
            .finished() // 查询已经完成的任务
            .list(); 
        List<TaskEntity> taskEntityList = new ArrayList<TaskEntity>();
        TaskEntity te = null;
        for(HistoricTaskInstance hti:list){
        	te = new TaskEntity();
            logger.info("任务ID:"+hti.getId());
            te.setId(hti.getId());
            logger.info("流程实例ID:"+hti.getProcessInstanceId());
            te.setProcessInstanceId(hti.getProcessInstanceId());
            logger.info("任务名称："+hti.getName());
            te.setName(hti.getName());
            logger.info("办理人："+hti.getAssignee());
            te.setAssignee(hti.getAssignee());
            logger.info("开始时间："+hti.getStartTime());
            te.setStartTime(hti.getStartTime());
            logger.info("结束时间："+hti.getEndTime());
            te.setEndTime(hti.getEndTime());
            logger.info("=================================");
            taskEntityList.add(te);
        }
        return taskEntityList;
    }
    /**
     * 查询流程状态（正在执行 or 已经执行结束）
     */
    public String processState(String processInstanceId){
    	String info = "流程实例id:"+processInstanceId;
        ProcessInstance pi= runtimeService // 获取运行时Service
            .createProcessInstanceQuery() // 创建流程实例查询
            .processInstanceId(processInstanceId) // 用流程实例id查询
            .singleResult();
        if(pi!=null){
        	info+="，流程正在执行！";
        }else{
        	info+="，流程已经执行结束！";
        }
        logger.info(info);
        return info;
    }

}
